/******************************************************************************************************
Copyright (C) 2019 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/
/*jslint indent: 4, maxerr: 50, plusplus: true */
/*globals Application, date2ISOString, Dir, Env, FileDialog, mainWindow, MessageBox, MnUi, ProgressDialog, serialization, settings*/

function exportSplitDocument() {
	"use strict";

	var allFilters, applyToAllKey, currentPage, dialog, doc, filterIndex, filterKey, filterList, folderKey, nameKey, pageIndex, pages;

	doc = mainWindow.activeDocument;
	if (!doc) {
		MessageBox.critical("Document not found");
		return;
	}

	dialog = Application.loadUiFile("ricares:exportSplitDocument.ui");
	folderKey = "Export Split Document/";
	applyToAllKey = folderKey + "Apply to All";
	filterKey = folderKey + "Save Format";
	nameKey = folderKey + "Name";
	pages = doc.pages();
	currentPage = doc.curPage();
	allFilters = [];

	for (pageIndex = 0; pageIndex < pages.length; ++pageIndex) {
		doc.setCurPage(pages[pageIndex]);
		filterList = serialization.saveFilters().split(";;");
		for (filterIndex = 0; filterIndex < filterList.length; ++filterIndex) {
			if (allFilters.indexOf(filterList[filterIndex]) === -1) {
				allFilters.push(filterList[filterIndex]);
			}
		}
	}

	for (filterIndex = 0; filterIndex < allFilters.length; ++filterIndex) {
		dialog.widgets.cbFormat.addItem(allFilters[filterIndex]);
	}

	doc.setCurPage(currentPage);
	dialog.widgets.cbFormat.currentText = settings.value(filterKey, "MestReNova Document (*.mnova)");
	dialog.widgets.cbApplyToAll.checked = settings.value(applyToAllKey, false);
	dialog.widgets.lineEditName.text = settings.value(nameKey, "%DOCUMENT_NAME%_Page_%PAGE_NUMBER%");

	function pad(n, width, z) {
		z = z || '0';
		n = String(n);
		return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
	}

	dialog.widgets.okButton.clicked.connect(function () {

		var applyToAll, dirKey, docName, i, page, pageNumber, dataDir, file, dir, filter, selectedPages, progress, extension, numberOfDigitsTotalPages, startDateDir, tempDoc, name;

		dirKey = "Export Split Document/Save Directory";
		applyToAll = dialog.widgets.cbApplyToAll.checked;
		filter = dialog.widgets.cbFormat.currentText;
		name = dialog.widgets.lineEditName.text;
		extension = filter.substring(filter.lastIndexOf("(") + 1, filter.lastIndexOf(")")).split(" ")[0].substr(1);
		settings.setValue(filterKey, filter);
		settings.setValue(applyToAllKey, applyToAll);
		settings.setValue(nameKey, name);
		selectedPages = doc.selectedPages();
		Env.converterUseDefaultSettings = false;

		if (doc.isValid()) {

			docName = doc.name.replace(/\.[^\/.]+$/, "").replace(/^.*[\\\/]/, "");

			if (selectedPages.length === 0) {
				selectedPages = doc.pages();
			}

			dataDir = FileDialog.getExistingDirectory(settings.value(dirKey, Dir.home()), "Select Directory to Save the Data");
			startDateDir = date2ISOString(new Date()).replace(new RegExp("\\:", 'g'), ".");

			if (dataDir !== "") {

				settings.setValue(dirKey, dataDir);
				dir = new Dir(dataDir);

				if (dir.exists) {

					dir.mkdir(startDateDir);
					dir.cd(startDateDir);
					progress = new ProgressDialog();
					progress.minimumDuration = 0;
					progress.setRange(0, selectedPages.length);
					progress.show();
					tempDoc = mainWindow.newWindow();
					numberOfDigitsTotalPages = selectedPages.length.toString().length;

					for (i = 0; i < selectedPages.length; i++) {

						if (progress.wasCanceled) {
							tempDoc.close();
							mainWindow.activeDocument = doc;
							Env.converterUseDefaultSettings = false;
							return;
						}

						if (i === 1) {
							Env.converterUseDefaultSettings = applyToAll;
						}

						page = selectedPages[i];
						progress.value = i;
						progress.labelText = "Saving page...\n {0} of {1}\n".replace('{0}', 1 + i).replace('{1}', selectedPages.length);
						tempDoc.deletePages(tempDoc.pages());
						tempDoc.clonePages(page);
						pageNumber = pad(parseInt(i + 1, 10), numberOfDigitsTotalPages);
						file = name.replace('%DOCUMENT_NAME%', docName).replace('%PAGE_NUMBER%', pageNumber).replace('%PAGE_TITLE%', page.title).replace(/(\r\n|\n|\r)/gm, "") + extension;
						serialization.save(dir.filePath(file), filter);
					}
					progress.close();
					tempDoc.close();
					mainWindow.activeDocument = doc;
				}
			}
		}
		Env.converterUseDefaultSettings = false;
	});

	dialog.exec();
}

if (this.MnUi && MnUi.scripts_common) {
	MnUi.scripts_common.scripts_common_ExportSplitDocument = exportSplitDocument;
}